Guide: Integrate TideCloak JS SDK with JavaScript
This guide will help you integrate TideCloak using JavaScript to manage user authentication. Follow the steps below to set up and customize the example provided.
Prerequisites
Before you begin, ensure that you have:
- A TideCloak instance running locally or on a server.
- A realm and a client configured in TideCloak.
- Basic knowledge of HTML and JavaScript.
- Python installed on your machine (for running a local server).
0: Set Up Tidecloak and Tide IDP
Before starting the integration, make sure you have both Tidecloak and the TIDE Identity Provider (IDP) set up and running. This is crucial for managing user authentication in your application. You can refer to the following setup guides:
- How to Set Up Tidecloak – In this guide, you will configure Tidecloak with the same values used in this tutorial (e.g.,
localhost:8000
for the app). - How to Set Up the TIDE IDP – This guide helps you configure the TIDE Identity Provider, which will serve as your authentication server.
By following these setup guides, you'll ensure your environment is ready to integrate with your app using the values provided in this tutorial. Please continue with the steps below to integrate Tide using JS.
1. Set Up the Project
1.1 Create the HTML File
First, create an HTML file. This file will be the foundation of your project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TideCloak Login Example</title>
<script src="https://cdn.jsdelivr.net/npm/keycloak-js@25.0.2/dist/keycloak.min.js"></script>
</head>
<body>
<h1>Welcome to TideCloak Login Example</h1>
<button onclick="login()">Hello</button>
<p id="message"></p>
<div id="user-info"></div>
<button id="logout-button" onclick="logout()" style="display:none;">Sign Out</button>
</body>
</html>
1.2 Include the Keycloak JavaScript Adapter via CDN
In the <head>
section of your HTML file, include the TideCloak JavaScript adapter using a CDN. This adapter is necessary to integrate TideCloak with your application.
<script src="https://cdn.jsdelivr.net/npm/keycloak-js@25.0.2/dist/keycloak.min.js"></script>
Your HTML file should now look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TideCloak Login Example</title>
<script src="https://cdn.jsdelivr.net/npm/keycloak-js@25.0.2/dist/keycloak.min.js"></script>
</head>
<body>
<h1>Welcome to TideCloak Login Example</h1>
<button onclick="login()">Hello</button>
<p id="message"></p>
<div id="user-info"></div>
<button id="logout-button" onclick="logout()" style="display:none;">Sign Out</button>
</body>
</html>
2. Initialize TideCloak
In your JavaScript code, initialize the TideCloak instance with the necessary configuration options.
var keycloak = new Keycloak({
url: 'http://localhost:8080',
realm: 'myrealm',
clientId: 'myclient'
});
If you are following along with our sample project, your values will be the same as those provided in this guide.
3. Implement the Login Function
Now that you have configured your TideCloak instance, included the TideCloak JavaScript adapter, and initialized the TideCloak client, you need to set up the login process for your project. To do this, you will use the TideCloak SDK's login()
method to redirect users to the TideCloak login page, where TideCloak can authenticate them. After a user successfully authenticates, they will be redirected to the callback URL you specified in the TideCloak configuration. This process ensures that users are authenticated before accessing your application.
function login() {
keycloak.init({
onLoad: 'check-sso'
}).then(function(authenticated) {
if (!authenticated) {
keycloak.login({ redirectUri: 'http://localhost:8000' });
} else {
displayUserInfo();
}
}).catch(function() {
console.log('Failed to initialize');
});
}
4. Implement Logout
Users who log in to your project will also need a way to log out. The TideCloak JavaScript adapter provides a logout()
method that you can use to log a user out of your application. When users log out, they will be redirected to the TideCloak logout endpoint, which will then immediately redirect them to your application using the redirectUri
that you specify when calling the logout()
function.
Here's how you can implement the logout functionality:
function logout() {
keycloak.logout({ redirectUri: 'http://localhost:8000' });
}
In this example, the redirectUri
parameter ensures that after logging out, users are directed back to your specified application URL. This allows for a seamless user experience where they can be redirected to a post-logout page or back to the main login page.
5. Display User Information
Now that your users can log in and log out, you will likely want to retrieve the profile information associated with authenticated users. For example, you may want to personalize the user interface by displaying the logged-in user's name, email, or other profile details.
The TideCloak JavaScript adapter provides user information through the loadUserProfile()
function. This function fetches the user's profile data, such as username, email, and full name, which you can then display on your webpage.
function displayUserInfo() {
keycloak.loadUserProfile().then(function(profile) {
document.getElementById('message').textContent = 'Welcome ' + profile.username;
document.getElementById('user-info').innerHTML = `
<p><strong>Username:</strong> ${profile.username}</p>
<p><strong>Email:</strong> ${profile.email || 'N/A'}</p>
<p><strong>First Name:</strong> ${profile.firstName || 'N/A'}</p>
<p><strong>Last Name:</strong> ${profile.lastName || 'N/A'}</p>
`;
document.getElementById('logout-button').style.display = 'block';
}).catch(function() {
console.log('Failed to load user profile');
});
}
In this example, the displayUserInfo()
function is used to load and display the user's profile information after they have successfully logged in. The function retrieves the user's profile details, such as username and email, and displays them in the designated sections of the HTML page.
6. Run the Code Using a Local Server
To run the example code, you'll need to use a local server. Python's built-in HTTP server is an easy way to do this.
Steps to Run the Code:
- Open a terminal or command prompt.
- Navigate to the directory where your HTML file is located.
- Run the following command to start a local server:
- For Python 3.x:
python -m http.server 8000
- For Python 3.x:
- Open your web browser and go to
http://localhost:8000
. You should see the HTML page you created.
7. Finish and Test
By following the steps above, you should now have a fully functional TideCloak login integration. Open your browser, navigate to http://localhost:8000
, and click the "Hello" button to initiate the login process. If everything is set up correctly, you’ll be able to log in, see your user information, and log out.
8. Try It Out: Full Example Code
To try out the TideCloak integration without going through each step, you can copy the complete code below and paste it into a new HTML file. Open the file in your browser to see the full example in action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TideCloak Login Example</title>
<script src="https://cdn.jsdelivr.net/npm/keycloak-js@25.0.2/dist/keycloak.min.js"></script>
<script>
var keycloak = new Keycloak({
url: 'http://localhost:8080', // Ensure this is correct
realm: 'myrealm',
clientId: 'myclient'
});
function login() {
keycloak.init({
onLoad: 'check-sso' // Use 'check-sso' to avoid immediate redirect
}).then(function(authenticated) {
if (!authenticated) {
keycloak.login({ redirectUri: 'http://localhost:8000' }); // Explicitly handle redirectUri
} else {
displayUserInfo();
}
}).catch(function() {
console.log('Failed to initialize');
});
}
function displayUserInfo() {
keycloak.loadUserProfile().then(function(profile) {
document.getElementById('message').textContent = 'Welcome ' + profile.username;
document.getElementById('user-info').innerHTML = `
`;
document.getElementById('logout-button').style.display = 'block';
}).catch(function() {
console.log('Failed to load user profile');
});
}
function logout() {
keycloak.logout({ redirectUri: 'http://localhost:8000' });
}
</script>
</head>
<body>
<h1>Welcome to TideCloak Login Example</h1>
<button onclick="login()">Hello</button>
<p id="message"></p>
<div id="user-info"></div>
<button id="logout-button" onclick="logout()" style="display:none;">Sign Out</button>
</body>
</html>
🎉 Congratulations on integrating the TideCloak SDK Using JavaScript! 🎉 You've just unlocked enhanced security for your cleint setup by integrating it with TideCloak. This integration brings together the best of both worlds, with Tide's advanced cybersecurity fabric. You're now ready to manage user authentication with heightened security and efficiency.